package com.dabai.addtofavorites.utils;

import android.content.Context;

import com.dabai.addtofavorites.bean.FavData;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class MyFileUtils {

    public static void delAll(Context context){
        File rootDir = new File(context.getFilesDir()+"/MyFiles/");
        FileUtils.delete(rootDir.getAbsolutePath());
    }

    private MyFileUtils(){}

    public static boolean createFile(Context context,FavData favData){

        File dir = new File(context.getFilesDir()+"/MyFiles/"+ DateUtils.getNowTime("yyyyMMdd"));
        if (!dir.exists()){
            dir.mkdirs();
        }

        File file = new File(dir,DateUtils.getNowTime("hhmmss"));

        if (file.exists()){
            return false;
        }

        return FileUtils.writeText(file.getAbsolutePath(),favData.getContent());
    }

    public static List<FavData> getAllFile(Context context){
        File rootDir = new File(context.getFilesDir()+"/MyFiles/");
        if (!rootDir.exists()){
            rootDir.mkdirs();
        }

        ArrayList<FavData> arrayList = new ArrayList<>();

        File[] rootDirs = rootDir.listFiles();
        Arrays.sort(rootDirs, new CompratorByLastModified(false));

        for (File dirs : rootDirs){
            File[] files = Objects.requireNonNull(dirs.listFiles());
            Arrays.sort(files, new CompratorByLastModified(false));
            for (File file : files){
                FavData favData = new FavData();
                favData.setContent(FileUtils.readText(file.getAbsolutePath()));
                favData.setFile(file);
                arrayList.add(favData);
            }
        }

        return arrayList;
    }


}
